package com.one.group.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.one.group.admin.mapper.QuestionMapper;
import com.one.group.admin.mapper.QuestionOptionMapper;
import com.one.group.model.dto.QuestionDto;
import com.one.group.model.entity.Question;
import com.one.group.model.vo.QuestionDetailVo;
import com.one.group.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 问题服务实现类
 * @author kld
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
    
    // 获取租户ID的辅助方法
    private Long getCurrentTenantId() {
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
        log.debug("当前租户ID: {}", tenantId);
        return tenantId;
    }

    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private QuestionOptionMapper questionOptionMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addQuestion(QuestionDto addDto) {
        Long tenantId = getCurrentTenantId();
        // 获取当前问卷的最大题号
        Integer maxSort = questionMapper.getMaxSortByQuestionnaireId(addDto.getQuestionnaireId(), tenantId);
        // 设置新问题的序号，如果没有问题则从1开始
        Integer newSort = (maxSort == null) ? 1 : maxSort + 1;
        
        // 创建问题实体
        Question question = new Question();
        question.setQuestionnaireId(addDto.getQuestionnaireId());
        question.setType(addDto.getType());
        question.setQuestion(addDto.getQuestion());
        question.setSort(newSort);
        question.setIsRequired(addDto.getIsRequired());
        question.setTenantId(tenantId);
        
        // 保存问题
        if (!save(question)) {
            log.debug("添加问题失败，问卷ID: {}, 问题内容: {}", addDto.getQuestionnaireId(), addDto.getQuestion());
            return false;
        }
        log.debug("添加问题成功，问题ID: {}, 问题内容: {}", question.getQuestionId(), question.getQuestion());
        return true;
    }
    
    @Override
    public QuestionDetailVo getQuestionDetail(Long questionId) {
        Long tenantId = getCurrentTenantId();
        // 查询问题详情
        return questionMapper.getQuestionDetail(questionId, tenantId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateQuestion(Long questionId, QuestionDto addDto) {
        Long tenantId = getCurrentTenantId();
        // 验证问题是否存在且属于当前租户
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq("question_id", questionId)
                .eq("tenant_id", tenantId);
        
        Question existingQuestion = getOne(queryWrapper);
        if (existingQuestion == null) {
            log.debug("更新问题失败，问题不存在或不属于当前租户，问题ID: {}, 租户ID: {}", questionId, tenantId);
            return false;
        }
        
        // 更新问题基本信息
        existingQuestion.setType(addDto.getType());
        existingQuestion.setQuestion(addDto.getQuestion());
        existingQuestion.setIsRequired(addDto.getIsRequired());
        // 添加排序字段更新
        if (addDto.getSort() != null) {
            existingQuestion.setSort(addDto.getSort());
        }
        
        if (!updateById(existingQuestion)) {
            log.debug("更新问题失败，问题ID: {}, 问题内容: {}", questionId, addDto.getQuestion());
            return false;
        }
        log.debug("更新问题成功，问题ID: {}, 问题内容: {}", questionId, existingQuestion.getQuestion());
        return true;
    }
    @Override
    public List<QuestionDetailVo> getQuestionsByQuestionnaireId(Long questionnaireId) {
        Long tenantId = getCurrentTenantId();
        // 查询问卷下所有问题及选项，按问题排序和选项排序
        return questionMapper.getQuestionsByQuestionnaireId(questionnaireId, tenantId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteQuestion(Long questionId) {
        Long tenantId = getCurrentTenantId();
        // 验证问题是否存在且属于当前租户
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq("question_id", questionId);

        Question existingQuestion = getOne(queryWrapper);
        if (existingQuestion == null) {
            return false; // 问题不存在或不属于当前租户
        }
        
        // 先删除问题的所有选项
        questionMapper.deleteOptionsByQuestionId(questionId, tenantId);
        
        // 再删除问题本身
        boolean result = removeById(questionId);
        if (result) {
            log.debug("删除问题成功，问题ID: {}, 问题内容: {}", questionId, existingQuestion.getQuestion());
        } else {
            log.debug("删除问题失败，问题ID: {}, 问题内容: {}", questionId, existingQuestion.getQuestion());
        }
        return result;
    }
    
    @Override
    public boolean deleteOption(Long optionId) {
        Long tenantId = getCurrentTenantId();
        // 验证选项是否存在且属于当前租户
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq("option_id", optionId)
                .eq("tenant_id", tenantId);
        
        // 执行删除操作
        boolean result = questionOptionMapper.deleteByQuery(queryWrapper) > 0;
        if (result) {
            log.debug("删除问题选项成功，选项ID: {}, 租户ID: {}", optionId, tenantId);
        } else {
            log.debug("删除问题选项失败，选项ID: {}, 租户ID: {}", optionId, tenantId);
        }
        return result;
    }
    
    @Override
    public boolean batchUpdateQuestionSort(Long questionnaireId) {
        // 参数校验
        if (questionnaireId == null) {
            log.debug("问卷ID不能为空");
            return false;
        }
        
        Long tenantId = getCurrentTenantId();
        log.debug("开始对问卷问题进行排序，问卷ID: {}, 租户ID: {}", questionnaireId, tenantId);
        
        // 调用mapper进行排序更新
        boolean result = questionMapper.batchUpdateQuestionSort(questionnaireId, tenantId);
        
        if (result) {
            log.debug("问卷问题排序成功，问卷ID: {}, 租户ID: {}", questionnaireId, tenantId);
        } else {
            log.debug("问卷问题排序失败，问卷ID: {}, 租户ID: {}", questionnaireId, tenantId);
        }
        
        return result;
    }
}